package com.jlect.swebing.ui.client;

import java.util.Iterator;

/**
 * Class implements linear iteration through the components children at once.
 *
 * @author Sergey Kozmin
 * @since 26.11.2007 10:48:30
 */
public class ChildLinearTraversalPolicy implements FocusTraversalPolicy {
    private ComponentsProvider baseComponent;

    public ChildLinearTraversalPolicy(ComponentsProvider baseComponent) {
        this.baseComponent = baseComponent;
    }

    public GComponent getComponentAfter(GComponent component) {
        Iterator componentsIterator = baseComponent.getComponentsIterator();
        while (componentsIterator.hasNext()) {
            Object comp = componentsIterator.next();
            if(comp.equals(component)) {
                return componentsIterator.hasNext() ? (GComponent)componentsIterator.next() : null;
            }
        }
        return null;
    }

    public GComponent getComponentBefore(GComponent component) {
        Iterator componentsIterator = baseComponent.getComponentsIterator();
        Object prevComp = null;
        while (componentsIterator.hasNext()) {
            Object comp = componentsIterator.next();
            if(comp.equals(component)) {
                return (GComponent) prevComp;
            }
            prevComp = comp;
        }
        return null;
    }

    public GComponent getFirstComponent() {
        return baseComponent.getComponentsCount() > 0 ? baseComponent.getComponentByIndex(0) : null;
    }

    public GComponent getLastComponent() {
        return baseComponent.getComponentsCount() > 0 ?
                baseComponent.getComponentByIndex(baseComponent.getComponentsCount() - 1) 
                : null;
    }
}
